package function;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import tool.Log;

import boot.Boot;
import db.SimpleDBListener;
import db.SimpleDBReader;
import files.Files;

public class NavigatorReloader {

	private static final String EXTENSION = "pdb";
	private ChainMp3 reloadedData;

	public ChainMp3 getReloadedData() throws NoDataException {
		return getReloadedData(NavigatorSaver.FILE_PATH);
	}

	private class InnerListener implements SimpleDBListener {

		public void processLine(String line) {
			Mp3File file = new Mp3File(line);

			if (reloadedData == null) {
				reloadedData = new ChainMp3Impl(file, null, null);
			} else {
				reloadedData.setLast(file);
			}

		}

		public void readingDone() {
			// Do nothing
		}

	}

	private ChainMp3 getReloadedData(String aFilePath) throws NoDataException {
		reloadedData = null;
		FileConnection fc;
		try {
			fc = (FileConnection) Connector.open(aFilePath);
			if (!fc.exists()) {
				throw new NoDataException();
			}
			fc.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "getReloadedData()");
		}
		SimpleDBReader dbr = new SimpleDBReader(aFilePath);
		dbr.addListener(new InnerListener());
		dbr.readDB();

		return reloadedData;
	}

	public ChainMp3 getPlaylist(String name) throws NoDataException {
		String path = Files.PLAYLIST_PATH + "/" + name + "." + EXTENSION;
		Log.log(path);
		return getReloadedData(path);
	}
}
